package com.atguigu.chapter09;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/10 9:51
 */
public class Flink10_CEP_After {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .readTextFile("input/sensor-cep.csv")
//                .socketTextStream("localhost",9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forMonotonousTimestamps()
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        Pattern<WaterSensor, WaterSensor> pattern = Pattern
//                .<WaterSensor>begin("start", AfterMatchSkipStrategy.noSkip())   // 默认的，不跳过
//                .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToNext())   // 相同的开头 丢弃掉
//                .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipPastLastEvent())   // 把正常第一次匹配的结果，当成最终的结果，其他结果都丢弃
                .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToFirst("start")) // 指定名称的事件 有多个匹配，只保留第一条，在它之前的 所有匹配 丢弃掉（不考虑最开始的基准结果）
//                .<WaterSensor>begin("start", AfterMatchSkipStrategy.skipToLast("start")) // 指定名称的事件 有多个匹配，只保留最后一个结果，在它之前的都丢弃（不考虑最开始的基准结果）
                .where(
                        new SimpleCondition<WaterSensor>() {

                            @Override
                            public boolean filter(WaterSensor value) throws Exception {
                                return "sensor_1".equals(value.getId());
                            }
                        }
                )
                .times(1,3)
                .next("next")
                .where(new SimpleCondition<WaterSensor>() {
                    @Override
                    public boolean filter(WaterSensor value) throws Exception {
                        return "sensor_2".equals(value.getId());
                    }
                });


        PatternStream<WaterSensor> sensorPS = CEP.pattern(sensorDS, pattern);

        SingleOutputStreamOperator<String> resultDS = sensorPS.select(new PatternSelectFunction<WaterSensor, String>() {
            @Override
            public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                return pattern.toString();
            }
        });

        resultDS.print();

        env.execute();
    }

}
/*
给定一组数字：
1  2  3  3  3  4

正则匹配规则：	以 1 或 2 或 3开头的完整的一段数据

匹配结果：
1  2  3  3  3  4
2  3  3  3  4
3  3  3  4
3  3  4
3  4


skipToFirst（3）：   以3开头的这个结果有多个， ToFirst，只保留第一条，在它之前的都丢掉
skipToLast（3）： 以3开头的这个结果有多个，ToLast，只取最后一个，在它前面的全部丢弃
 */